<?php
/**
 * Created by PhpStorm.
 * User: zen
 * Date: 2017/2/27
 * Time: 17:05
 */

namespace Lib;


class Application
{
    public $base_path;
    public $config;
    protected static $instance;

    protected function __construct($base_path)
    {
        $this->base_path = $base_path;
        $this->config = new Config($base_path . '/App/Config');
    }

    static function getInstance($base_path = '')
    {
        if (empty(self::$instance))
        {
            self::$instance = new self($base_path);
        }
        return self::$instance;
    }

    function dispatch()
    {
        $uri = $_SERVER['SCRIPT_NAME'];
        list($c, $v) = explode('/', trim(str_replace('index.php', '', $uri), '/'));

        $c_low = strtolower($c);
        $c = ucwords($c);
        $class = '\\App\\Controller\\'.$c;
        $obj = new $class($c, $v);

        $controller_config = $this->config['Controller'];
        $decorators = array();
        if (isset($controller_config[$c_low]['decorator']))
        {
            $conf_decorator = $controller_config[$c_low]['decorator'];
            foreach($conf_decorator as $class)
            {
                $decorators[] = new $class;
            }
        }
        foreach($decorators as $decorator)
        {
            $decorator->beforeRequest($obj);
        }
        $return_value = $obj->$v();
        foreach($decorators as $decorator)
        {
            $decorator->afterRequest($return_value);
        }
    }
}